package com.leTest.eduService.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.leTest.eduService.entity.SubjectEntity;
import com.leTest.eduService.entity.excel.SubjectData;
import com.leTest.eduService.service.SubjectService;
import com.leTest.exceptionhandler.CustomExceptionHandler;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    public SubjectService subjectService;
    public SubjectExcelListener() {}
    public SubjectExcelListener(SubjectService subjectService) {
        this.subjectService = subjectService;
    }

    //一行一行读取excel内容(从第二行开始读取,第一行是表头,该方法不会读取第一行)
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        //1.判断文件是否为空
        if (subjectData == null) {
            throw new CustomExceptionHandler(201, "文件数据为空");
        }

        //2.一行一行读取,每次读取有两个值,第一个值是一级分类,第二个值是二级分类
        //①添加一级分类
        SubjectEntity existOneSubject = this.existOneSubject(subjectService, subjectData.getOneSubjectName());
        if (existOneSubject == null) { //一级分类没有重复,进行添加
            existOneSubject = new SubjectEntity();
            existOneSubject.setParentId("0");
            existOneSubject.setTitle(subjectData.getOneSubjectName());
            subjectService.save(existOneSubject);
        }
        //②添加二级分类
        //先获得一级分类的id
        String pid = existOneSubject.getId();
        //再添加二级分类
        SubjectEntity existTwoSubject = this.existTwoSubject(subjectService,subjectData.getTwoSubjectName(), pid);
        if (existTwoSubject == null) { //二级分类没有重复,进行添加
            existTwoSubject = new SubjectEntity();
            existTwoSubject.setParentId(pid);
            existTwoSubject.setTitle(subjectData.getTwoSubjectName());
            subjectService.save(existTwoSubject);
        }
    }

    //判断一级分类是否重复
    private SubjectEntity existOneSubject(SubjectService subjectService, String name) {
        QueryWrapper<SubjectEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", "0");
        SubjectEntity oneSubject = subjectService.getOne(wrapper);
        return oneSubject;
    }

    //判断二级分类是否重复
    private SubjectEntity existTwoSubject(SubjectService subjectService, String name, String pid) {
        QueryWrapper<SubjectEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", pid);
        SubjectEntity twoSubject = subjectService.getOne(wrapper);
        return twoSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
